<template>
  <div class="transactions-container">
    <h2>交易列表</h2>
    <div v-if="loading" class="loading-message">加载中...</div>
    <div v-else-if="error" class="error-message">{{ error }}</div>
    <ul v-else>
      <li v-for="transaction in sortedTransactions" :key="transaction.transaction_id">
        <div>类型: <span :class="{'income': transaction.type === 'income', 'expense': transaction.type === 'expense'}">{{ transaction.type }}</span></div>
        <div>金额: {{ transaction.amount }}</div>
        <div>类别: {{ transaction.category }}</div>
        <div>描述: {{ transaction.description }}</div>
        <button @click="deleteTransaction(transaction.transaction_id)">删除</button>
        <button @click="editTransactionModal(transaction)">编辑</button>
      </li>
    </ul>

    <div class="add-transaction">
      <h2>添加交易</h2>
      <form @submit.prevent="addTransaction">
        <label>
          类型:
          <select v-model="newTransaction.type">
            <option value="income">收入</option>
            <option value="expense">支出</option>
          </select>
        </label>
        <label>
          金额:
          <input type="number" v-model="newTransaction.amount">
        </label>
        <label>
          类别:
          <input type="text" v-model="newTransaction.category">
        </label>
        <label>
          描述:
          <input type="text" v-model="newTransaction.description">
        </label>
        <button type="submit">添加</button>
      </form>
    </div>

    <!-- 编辑交易的模态框 -->
    <div v-if="editModalVisible" class="modal">
      <div class="modal-content">
        <span class="close" @click="closeEditModal">&times;</span>
        <h2>编辑交易</h2>
        <form @submit.prevent="updateTransaction">
          <label>
            类型:
            <select v-model="editedTransaction.type">
              <option value="income">收入</option>
              <option value="expense">支出</option>
            </select>
          </label>
          <label>
            金额:
            <input type="number" v-model="editedTransaction.amount">
          </label>
          <label>
            类别:
            <input type="text" v-model="editedTransaction.category">
          </label>
          <label>
            描述:
            <input type="text" v-model="editedTransaction.description">
          </label>
          <button type="submit">保存</button>
        </form>
      </div>
    </div>
  </div>
</template>
<script>
import axios from 'axios'

export default {
  beforeRouteEnter (to, from, next) {
    next(vm => {
      vm.loadData()
    })
  },
  data () {
    return {
      transactions: [],
      loading: false,
      error: '',
      editModalVisible: false,
      editedTransaction: {
        transaction_id: null,
        type: 'income',
        amount: 0,
        category: '',
        description: ''
      },
      newTransaction: {
        type: 'income',
        amount: 0,
        category: '',
        description: ''
      }
    }
  },
  methods: {
    async loadData () {
      const token = localStorage.getItem('token')
      if (!token) {
        this.$router.push('/login')
        return
      }

      const config = {
        headers: {
          Authorization: `Bearer ${token}`
        }
      }

      this.loading = true
      try {
        const response = await axios.get('/transactions', config)
        this.transactions = response.data
        this.loading = false
      } catch (error) {
        this.handleError(error)
      }
    },
    handleError (error) {
      this.error = error.response ? error.response.data.message || '获取交易失败，请重试' : '网络错误，请检查您的网络连接'
      this.loading = false
      console.error('获取交易失败:', error.response ? error.response.data.message : error.message)
    },
    addTransaction () {
      const token = localStorage.getItem('token')
      if (!token) {
        this.$router.push('/login')
        return
      }

      const config = {
        headers: {
          Authorization: `Bearer ${token}`
        }
      }

      axios.post('/transactions', this.newTransaction, config)
        .then(response => {
          this.transactions.push(response.data)
          this.resetNewTransaction()
        })
        .catch(error => {
          this.handleError(error)
        })
    },
    deleteTransaction (transactionId) {
      const token = localStorage.getItem('token')
      if (!token) {
        this.$router.push('/login')
        return
      }

      const config = {
        headers: {
          Authorization: `Bearer ${token}`
        }
      }

      axios.delete(`/transactions/${transactionId}`, config)
        .then(() => {
          this.transactions = this.transactions.filter(transaction => transaction.transaction_id !== transactionId)
        })
        .catch(error => {
          this.handleError(error)
        })
    },
    editTransactionModal (transaction) {
      this.editedTransaction = {
        transaction_id: transaction.transaction_id,
        type: transaction.type,
        amount: transaction.amount,
        category: transaction.category,
        description: transaction.description
      }
      this.editModalVisible = true
    },
    closeEditModal () {
      this.editModalVisible = false
    },
    updateTransaction () {
      const token = localStorage.getItem('token')
      if (!token) {
        this.$router.push('/login')
        return
      }

      const config = {
        headers: {
          Authorization: `Bearer ${token}`
        }
      }

      axios.put(`/transactions/${this.editedTransaction.transaction_id}`, this.editedTransaction, config)
        .then(() => {
          this.closeEditModal()
          this.loadData()
        })
        .catch(error => {
          this.handleError(error)
        })
    },
    resetNewTransaction () {
      this.newTransaction = {
        type: 'income',
        amount: 0,
        category: '',
        description: ''
      }
    }
  },
  computed: {
    sortedTransactions () {
      return this.transactions
    }
  }
}
</script>
<style scoped>
.transactions-container {
  max-width: 600px;
  margin: 0 auto;
  padding: 20px;
  background-color: #f9f9f9;
  border-radius: 8px;
  box-shadow: 0 2px 8px rgba(0, 0, 0, 0.1);
}

h2 {
  text-align: center;
  margin-bottom: 20px;
  color: #333;
}

ul {
  list-style: none;
  padding: 0;
}

li {
  background-color: #fff;
  border: 1px solid #ddd;
  border-radius: 4px;
  margin-bottom: 10px;
  padding: 10px;
  display: flex;
  flex-direction: column;
  gap: 5px;
}

li div {
  margin-bottom: 5px;
}

button {
  margin-right: 5px;
  padding: 5px 10px;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

button:hover {
  background-color: #f0f0f0;
}

.income {
  color: green;
}

.expense {
  color: red;
}

.loading-message, .error-message {
  text-align: center;
  margin-top: 20px;
  font-style: italic;
  color: #555;
}

.add-transaction {
  margin-top: 30px;
}

.add-transaction form {
  display: flex;
  flex-direction: column;
  gap: 10px;
}

.add-transaction label {
  display: flex;
  justify-content: space-between;
  align-items: center;
}

.add-transaction input,
.add-transaction select {
  width: 60%;
  padding: 5px;
  border: 1px solid #ccc;
  border-radius: 4px;
}

.add-transaction button {
  align-self: center;
  padding: 8px 16px;
  background-color: #409eff;
  color: white;
  border: none;
  border-radius: 4px;
  cursor: pointer;
}

.add-transaction button:hover {
  background-color: #66b1ff;
}

/* 编辑交易的模态框样式 */
.modal {
  position: fixed;
  top: 0;
  left: 0;
  width: 100%;
  height: 100%;
  background-color: rgba(0, 0, 0, 0.5);
  display: flex;
  justify-content: center;
  align-items: center;
}

.modal-content {
  background-color: white;
  padding: 20px;
  border-radius: 8px;
  width: 90%;
  max-width: 500px;
  position: relative;
}

.close {
  position: absolute;
  top: 10px;
  right: 10px;
  font-size: 20px;
  cursor: pointer;
}
</style>
